
//
//  ISAACLoginController.m
//  FireBird
//
//  Created by Isaac on 2018/5/2.
//  Copyright © 2018年 Isaac. All rights reserved.
//

#import "ISAACLoginController.h"
#import "ISAACRegistController.h"
@interface ISAACLoginController ()

@property (nonatomic, strong)UITextField *accountText;
@property (nonatomic, strong)UITextField *pswText;

@property (nonatomic, strong)UIButton *getVericodeBtn;
@property (nonatomic, strong)UIButton *loginTypeBtn;
@property (nonatomic, strong)UIButton *registBtn;


@end

@implementation ISAACLoginController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self addTitleViewWithTitle:@"登录"];
    
    [self setupViews];
    
    [self addBarButtonItemWithFrame:CGRectMake(0, 0, 40, 40) WithTitle:@"" WithImage:[UIImage imageNamed:@"back"] target:self action:@selector(handleDismiss:) isLeft:YES];
    
}
- (void)setupViews {
    
    self.accountText = [MyControlUilt createTextFieldWithFrame:CGRectMake(LEFTSPACE, 120, SCREEN_WIDTH-LEFTSPACE*2, 30) Title:@"输入手机号" TextColor:kTextColorTwo SuperView:self.view Font:FONT14 BackColor:kBackGColor];
    
    self.pswText = [MyControlUilt createTextFieldWithFrame:CGRectMake(LEFTSPACE, CGRectGetMaxY(_accountText.frame), SCREEN_WIDTH-LEFTSPACE*2-100, 30) Title:@"输入验证码" TextColor:kTextColorTwo SuperView:self.view Font:FONT14 BackColor:kBackGColor];

    
    self.getVericodeBtn = [MyControlUilt createButtonWithFrame:CGRectMake(SCREEN_WIDTH-LEFTSPACE-100, CGRectGetMinY(_pswText.frame), 100, 30) Title:@"获取验证码" TiTleColor:kRedColor SuperView:self.view Font:FONT14 BackColor:kBackGColor];
    [_getVericodeBtn addTarget:self action:@selector(handleGetVerifyCode:) forControlEvents:UIControlEventTouchUpInside];

    
    self.loginTypeBtn = [MyControlUilt createButtonWithFrame:CGRectMake(LEFTSPACE, CGRectGetMaxY(_pswText.frame)+10, 100, 30) Title:@"账号密码登录" TiTleColor:kTextColorTwo SuperView:self.view Font:FONT14 BackColor:kBackGColor];
    [_loginTypeBtn addTarget:self action:@selector(handleLoginType:) forControlEvents:UIControlEventTouchUpInside];
    [_loginTypeBtn setTitle:@"验证码登录" forState:UIControlStateSelected];
    
    
    self.registBtn = [MyControlUilt createButtonWithFrame:CGRectMake(SCREEN_WIDTH-LEFTSPACE-100, CGRectGetMinY(_loginTypeBtn.frame), 100, 30) Title:@"快速注册" TiTleColor:kTextColorTwo SuperView:self.view Font:FONT14 BackColor:kBackGColor];
    [_registBtn addTarget:self action:@selector(handleRegist:) forControlEvents:UIControlEventTouchUpInside];

    
    UIButton *confirmBtn = [MyControlUilt createButtonWithFrame:CGRectMake((SCREEN_WIDTH-200)/2.0, CGRectGetMaxY(_loginTypeBtn.frame) + 40, 200, 42) Title:@"登录" TiTleColor:kWhiteColor SuperView:self.view Font:FONT14 BackColor:kRedColor];
    confirmBtn.layer.masksToBounds = YES;
    confirmBtn.layer.cornerRadius = 21;
    [confirmBtn addTarget:self action:@selector(handleConfirmLogin:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *QQBtn = [MyControlUilt createButtonWithFrame:CGRectMake(SCREEN_WIDTH/2.0-40-40-80, SCREEN_HEIGHT-140, 80, 100) Title:@"微信登录" TiTleColor:kTextColorTwo SuperView:self.view Font:FONT14 BackColor:nil];
    QQBtn.tag = 120;
    [QQBtn setImage:[UIImage imageNamed:@"微信"] forState:UIControlStateNormal];
    [QQBtn verticalImageAndTitle:5];
    [QQBtn addTarget:self action:@selector(handleThirdLogin:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *wechatBtn = [MyControlUilt createButtonWithFrame:CGRectMake(SCREEN_WIDTH/2.0-40, SCREEN_HEIGHT-140, 80, 100) Title:@"QQ登录" TiTleColor:kTextColorTwo SuperView:self.view Font:FONT14 BackColor:nil];
    wechatBtn.tag = 121;
    [wechatBtn setImage:[UIImage imageNamed:@"qq"] forState:UIControlStateNormal];
    [wechatBtn verticalImageAndTitle:5];
    [wechatBtn addTarget:self action:@selector(handleThirdLogin:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *weiboBtn = [MyControlUilt createButtonWithFrame:CGRectMake(SCREEN_WIDTH/2.0+40+40, SCREEN_HEIGHT-140, 80, 100) Title:@"微博登录" TiTleColor:kTextColorTwo SuperView:self.view Font:FONT14 BackColor:nil];
    weiboBtn.tag = 122;
    [weiboBtn setImage:[UIImage imageNamed:@"微博"] forState:UIControlStateNormal];
    [weiboBtn verticalImageAndTitle:5];
    [weiboBtn addTarget:self action:@selector(handleThirdLogin:) forControlEvents:UIControlEventTouchUpInside];
    
    
}
- (void)handleDismiss:(UIButton *)sender {
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (void)handleThirdLogin:(UIButton *)sender {
    if(sender.tag == 120) {
        [self fetchData:UMSocialPlatformType_WechatSession];
    }else if (sender.tag == 121) {
        [self fetchData:UMSocialPlatformType_QQ];
    }else {
        [self fetchData:UMSocialPlatformType_Sina];
    }
}
- (void)fetchData:(UMSocialPlatformType)type
{
    __weak ISAACLoginController *ws = self;
    
    //6.1版本已经修正了getUserInfoWithPlatform，每次获得用户都需要跳转授权
    //如果不需要每次跳转，可以查看[UMSocialGlobal shareInstance].isClearCacheWhenGetUserInfo,来设置
    //[[UMSocialManager defaultManager] cancelAuthWithPlatform:self.authInfo.platform completion:^(id result, NSError *error) {

    [[UMSocialManager defaultManager] getUserInfoWithPlatform:type currentViewController:self completion:^(id result, NSError *error) {
            
            NSString *message = nil;
            
            if (error) {
                message = [NSString stringWithFormat:@"Get info fail:\n%@", error];
                UMSocialLogInfo(@"Get info fail with error %@",error);
            }else{
                if ([result isKindOfClass:[UMSocialUserInfoResponse class]]) {
                    
                    UMSocialUserInfoResponse *resp = result;
                    
                    NSLog(@"QQ uid: %@", resp.uid);
                    NSLog(@"QQ openid: %@", resp.openid);
                    NSLog(@"QQ accessToken: %@", resp.accessToken);
                    NSLog(@"QQ expiration: %@", resp.expiration);
                    // 用户信息
                    NSLog(@"QQ name: %@", resp.name);
                    NSLog(@"QQ iconurl: %@", resp.iconurl);
                    NSLog(@"QQ gender: %@", resp.gender);
                    // 第三方平台SDK源数据
                    NSLog(@"QQ originalResponse: %@", resp.originalResponse);
                    NSLog(@"umeng:  %@",resp);
                    
//                    ws.authInfo.response = resp;
//
//                    message = [ws authInfoString:resp];
                }else{
                    message = @"Get info fail";
                }
            }
        }];
        //}];
    
}

/*
 QQ:
 UMSocialUserInfoResponse *resp = result;
 // 授权信息
 NSLog(@"QQ uid: %@", resp.uid);
 NSLog(@"QQ openid: %@", resp.openid);
 NSLog(@"QQ accessToken: %@", resp.accessToken);
 NSLog(@"QQ expiration: %@", resp.expiration);
 // 用户信息
 NSLog(@"QQ name: %@", resp.name);
 NSLog(@"QQ iconurl: %@", resp.iconurl);
 NSLog(@"QQ gender: %@", resp.gender);
 // 第三方平台SDK源数据
 NSLog(@"QQ originalResponse: %@", resp.originalResponse);
 
 【
 QQ uid: B5CCC5C4F4CCBB508B97638EB1520FE9
 2018-05-25 15:37:40.710  QQ openid: B5CCC5C4F4CCBB508B97638EB1520FE9
 2018-05-25 15:37:40.710  QQ accessToken: B5FA1D178D176CCA422FD07CCF584594
 2018-05-25 15:37:40.711  QQ expiration: 2018-08-23 07:37:39 +0000
 2018-05-25 15:37:40.712  QQ name: lsaac Yun
 2018-05-25 15:37:40.712  QQ iconurl: https://thirdqq.qlogo.cn/qqapp/1104660765/B5CCC5C4F4CCBB508B97638EB1520FE9/100
 2018-05-25 15:37:40.712  QQ gender: 男
 2018-05-25 15:37:40.713  QQ originalResponse: {
 city = "\U676d\U5dde";
 figureurl = "http://qzapp.qlogo.cn/qzapp/1104660765/B5CCC5C4F4CCBB508B97638EB1520FE9/30";
 "figureurl_1" = "http://qzapp.qlogo.cn/qzapp/1104660765/B5CCC5C4F4CCBB508B97638EB1520FE9/50";
 "figureurl_2" = "http://qzapp.qlogo.cn/qzapp/1104660765/B5CCC5C4F4CCBB508B97638EB1520FE9/100";
 "figureurl_qq_1" = "http://thirdqq.qlogo.cn/qqapp/1104660765/B5CCC5C4F4CCBB508B97638EB1520FE9/40";
 "figureurl_qq_2" = "http://thirdqq.qlogo.cn/qqapp/1104660765/B5CCC5C4F4CCBB508B97638EB1520FE9/100";
 gender = "\U7537";
 "is_lost" = 0;
 "is_yellow_vip" = 0;
 "is_yellow_year_vip" = 0;
 level = 0;
 msg = "";
 nickname = "lsaac Yun";
 province = "\U6d59\U6c5f";
 ret = 0;
 vip = 0;
 year = 1992;
 "yellow_vip_level" = 0;
 }
 】
 
 
 微信：
 UMSocialUserInfoResponse *resp = result;
 // 授权信息
 NSLog(@"Wechat uid: %@", resp.uid);
 NSLog(@"Wechat openid: %@", resp.openid);
 NSLog(@"Wechat accessToken: %@", resp.accessToken);
 NSLog(@"Wechat refreshToken: %@", resp.refreshToken);
 NSLog(@"Wechat expiration: %@", resp.expiration);
 // 用户信息
 NSLog(@"Wechat name: %@", resp.name);
 NSLog(@"Wechat iconurl: %@", resp.iconurl);
 NSLog(@"Wechat gender: %@", resp.gender);
 // 第三方平台SDK源数据
 NSLog(@"Wechat originalResponse: %@", resp.originalResponse);
 
 微博：
 NSLog(@" uid: %@", resp.uid);
 NSLog(@" openid: %@", resp.openid);
 NSLog(@" accessToken: %@", resp.accessToken);
 NSLog(@" refreshToken: %@", resp.refreshToken);
 NSLog(@" expiration: %@", resp.expiration);
 // 用户数据
 NSLog(@" name: %@", resp.name);
 NSLog(@" iconurl: %@", resp.iconurl);
 NSLog(@" gender: %@", resp.gender);
 // 第三方平台SDK原始数据
 NSLog(@" originalResponse: %@", resp.originalResponse);
 
 */



- (void)handleGetVerifyCode:(UIButton *)sender {
    if (_accountText.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号"];
        return;
    }
    if (![TTConfig validateMobile:_accountText.text]) {
        [SVProgressHUD showErrorWithStatus:@"手机号不正确"];
        return;
    }
    __block int timeout=60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [sender setTitle:@"发送验证码" forState:UIControlStateNormal];
                sender.userInteractionEnabled = YES;
            });
        }else{
            NSInteger seconds = timeout % 61;
            NSString *strTime = [NSString stringWithFormat:@"%ld", (long)seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                //NSLog(@"____%@",strTime);
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:1];
                [sender setTitle:[NSString stringWithFormat:@"%@秒",strTime] forState:UIControlStateNormal];
                [UIView commitAnimations];
                sender.userInteractionEnabled = NO;
            });
            timeout--;
        }
        
    });
    dispatch_resume(_timer);
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"phone"] = _accountText.text;
    param[@"type"] = @(1);
    
    //  去获取验证码
    __weak typeof(self) weakself = self;
    [TTServerTool postDictionaryResult:API_sms_send param:param isNeedToken:YES complete:^(BOOL network, TTPublicResult * result, NSError * error) {
        
        if (network) {
            
            if (result) {
                
                if([result.ErrorCode isEqualToString:@"0"]){
                    [weakself.pswText becomeFirstResponder];
                    
                    
                }else{
                    [SVProgressHUD showErrorWithStatus:result.ErrorMsg];
                    //倒计时结束，关闭
                    dispatch_source_cancel(_timer);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        //设置界面的按钮显示 根据自己需求设置
                        [sender setTitle:@"发送验证码" forState:UIControlStateNormal];
                        sender.userInteractionEnabled = YES;
                    });
                }
                
            }else{
                [SVProgressHUD showErrorWithStatus:@"暂无数据"];
                //倒计时结束，关闭
                dispatch_source_cancel(_timer);
                dispatch_async(dispatch_get_main_queue(), ^{
                    //设置界面的按钮显示 根据自己需求设置
                    [sender setTitle:@"发送验证码" forState:UIControlStateNormal];
                    sender.userInteractionEnabled = YES;
                });
            }
            
        }else{
            [SVProgressHUD showErrorWithStatus:@"网络错误"];
            //网络链接失败
            //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [sender setTitle:@"发送验证码" forState:UIControlStateNormal];
                sender.userInteractionEnabled = YES;
            });
        }
        
    }];
}
- (void)handleLoginType:(UIButton *)sender {
    sender.selected = !sender.selected;
    
    if(sender.selected) {
        _pswText.placeholder = @"输入密码";
        [_getVericodeBtn setTitle:@"忘记密码" forState:UIControlStateNormal];
        
    }else {
        _pswText.placeholder = @"输入验证码";
        [_getVericodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    }
    
}
- (void)handleRegist:(UIButton *)sender {
    ISAACRegistController *registVC = [[ISAACRegistController alloc] init];
    [self pushViewController:registVC animate:YES];
}
- (void)handleConfirmLogin:(UIButton *)sender {
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"user_name"] = _accountText.text;
    if ([_loginTypeBtn.titleLabel.text isEqualToString:@"验证码登录"]) {
        param[@"login_mod"] = @(2);
        param[@"password"] = _pswText.text;
    }else {
        param[@"login_mod"] = @(1);
        param[@"verify_code"] = _pswText.text;
    }

//    param[@"ACOS"] = @"iOS";
    
    __weak typeof(self) weakself = self;
    [TTServerTool postDictionaryResult:API_user_login param:param isNeedToken:YES complete:^(BOOL network, TTPublicResult * result, NSError * error) {
        
        if (network) {
            
            if (result) {
                
                if([result.ErrorCode isEqualToString:@"0"]){
                    [weakself.pswText becomeFirstResponder];
                    [weakself.navigationController dismissViewControllerAnimated:YES completion:^{
                        
                    }];
                    [self handelSaveInfo:result.Data];
                    
                }else{
                    [SVProgressHUD showErrorWithStatus:result.ErrorMsg];
                    //倒计时结束，关闭
                    
                }
                
            }else{
                [SVProgressHUD showErrorWithStatus:@"暂无数据"];
                //倒计时结束，关闭
                
            }
            
        }else{
            [SVProgressHUD showErrorWithStatus:@"网络错误"];
            //网络链接失败
            //倒计时结束，关闭
            
        }
        
    }];
}

- (void)handelSaveInfo:(NSDictionary *)dic {
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    [ud setObject: _accountText.text forKey:@"phone"];
    [ud setObject: _pswText.text forKey:@"password"];
    [ud setObject: dic[@"token"] forKey:@"token"];
    [ud setObject: dic[@"login_num"] forKey:@"login_num"];
    [ud setObject: dic[@"nick_name"] forKey:@"nick_name"];
    [ud setObject: dic[@"pid"] forKey:@"pid"];
    [ud setObject: dic[@"id"] forKey:@"nid"];
    [ud setObject: dic[@"rec_sn"] forKey:@"rec_sn"];
    [ud setObject: dic[@"user_name"] forKey:@"user_name"];
    
    
    [ud setObject: dic[@"user_type_id"] forKey:@"user_type_id"];
//    [ud setObject: dic[@"qr_code"] forKey:@"qr_code"];
//    [ud setObject: dic[@"user_name"] forKey:@"user_name"];
//    [ud setObject: dic[@"headimgurl"] forKey:@"headimgurl"];
//    [ud setObject: dic[@"role"] forKey:@"role"];
//    [ud setObject: dic[@"id_card"] forKey:@"id_card"];
//    [ud setObject: dic[@"total_customer"] forKey:@"total_customer"];
    
    
    [ud synchronize];
    
    
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(networkDidLogin:)
//                                                 name:kJPFNetworkDidLoginNotification
//                                               object:nil];
    
//    [JPUSHService setTags:[NSSet setWithObjects:[NSString stringWithFormat:@"%@",dic[@"role"]], nil] alias:[NSString stringWithFormat:@"%@",dic[@"id"]] callbackSelector:@selector(tagsAliasCallback:tags:alias:) object:self];
    
}
- (void)networkDidLogin:(NSNotification *)notification {
    NSLog(@"已登录");
//    [JPUSHService setAlias:@"123456" callbackSelector:nil object:nil];
//    [[NSNotificationCenter defaultCenter] removeObserver:self
//                                                    name:kJPFNetworkDidLoginNotification
//                                                  object:nil];
}


- (void)tagsAliasCallback:(int)iResCode tags:(NSSet*)tags alias:(NSString*)alias {
    
    NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, tags , alias);
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
